import { useCallback, useRef, useState } from 'react';
/**
 * 通用请求hook
 */
export const useFetch = (fetch, config = {}, initialLoading = true, initData) => {
    const [loading, setLoading] = useState(initialLoading);
    const [data, setData] = useState(initData);
    const [error, setError] = useState();
    const fetchRef = useRef(fetch);
    fetchRef.current = fetch;
    const wrapperFetch = useCallback(async (params) => {
        setLoading(true);
        try {
            const ret = await (async () => {
                if (Array.isArray(params)) {
                    return await fetchRef.current(params);
                } else {
                    return await fetchRef.current({ ...config, ...params });
                }
            })();
            setData(ret);
            setLoading(false);
            return ret;
        }
        catch (_error) {
            console.log(_error);
            setLoading(false);
            setError(_error);
            return undefined;
        }
    }, []);
    return { loading, data, fetch: wrapperFetch, updateData: setData, setLoading, error };
};
